import { RGBAImage } from "../util/Image";
import { Ajax } from "../util/Ajax";
import { StyleImage } from "./StyleImage";

export function loadSprite(
  baseURL: string,
  callback: (err: Error | null, images?: { [key: string]: StyleImage }) => void
) {
  if (!baseURL) {
    callback(null, {});
    return;
  }

  let json: any, image: HTMLImageElement | undefined, error: Error | null;
  const format = window.devicePixelRatio > 1 ? "@2x" : "";

  Ajax.getJSON(
    { url: `${baseURL}/sprite${format}.json` },
    (err: Error | null, data: any) => {
      if (!error) {
        error = err;
        json = data;
        maybeComplete();
      }
    }
  );

  Ajax.getImage({ url: `${baseURL}/sprite${format}.png` }, (err, img) => {
    if (!error) {
      error = err;
      image = img;
      maybeComplete();
    }
  });

  function maybeComplete() {
    if (error) {
      callback(error);
    } else if (json && image) {
      const imageData = getImageData(image);
      const result = {};

      for (const id in json) {
        const { width, height, x, y, sdf, pixelRatio } = json[id];
        const data = RGBAImage.create({ width, height });
        RGBAImage.copy(
          imageData,
          data,
          { x, y },
          { x: 0, y: 0 },
          { width, height }
        );
        result[id] = { data, pixelRatio, sdf };
      }

      callback(null, result);
    }
  }
}

function getImageData(img: HTMLImageElement): ImageData {
  const canvas = window.document.createElement("canvas");
  const context = canvas.getContext("2d");
  if (!context) {
    throw new Error("failed to create canvas 2d context");
  }
  canvas.width = img.width;
  canvas.height = img.height;
  context.drawImage(img, 0, 0, img.width, img.height);
  return context.getImageData(0, 0, img.width, img.height);
}
